package com.tanjie.blackbean.mqtt.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: tanjie
 * @date: 2022-03-01
 **/
@Slf4j
public class BlackbeanMqttUtil {

    public static final Map<String, MqttPahoMessageHandler> PRODUCER_MAP = new HashMap<>(16);

    /**
     * 使用消息处理器给主题发送消息
     */
    public static void send(String handlerName, String topic, Object data) {
        MqttPahoMessageHandler handler = PRODUCER_MAP.get(handlerName);
        if (handler == null) {
            log.error("mqtt消息发送处理器名称:{}不存在", handlerName);
            return;
        }
        Message<Object> mqttMessage = MessageBuilder
                .withPayload(data)
                .setHeader(MqttHeaders.TOPIC, topic)
                .setHeaderIfAbsent(MqttHeaders.QOS, 1)
                .build();
        handler.handleMessage(mqttMessage);
        log.info("MQTT: 向主题{}发送消息", topic);
    }

}
